package com.ruoyi.web.controller.system;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.QQSMSUtils;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Slf4j
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private RedisCache redisCache ;

    @Autowired
    private ISysUserService userService ;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    @PostMapping("/getEmailCode")
    public AjaxResult getEmailCode(@RequestBody HashMap<String,String> map){


        String emailCode = UUID.randomUUID().toString().substring(0, 5);
        String email = map.get("email");
        if (org.apache.commons.lang3.StringUtils.isBlank(email)){
            throw new ServiceException("邮箱不能为空！") ;
        }
//        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(SysUser::getEmail,email) ;
//        List<SysUser> list = userService.list(wrapper);
//        if (!CollectionUtils.isEmpty(list)){
//            throw new ServiceException("邮箱已存在！") ;
//
//        }
        if (!email.contains("qq")){
            throw new ServiceException("邮箱需要为qq邮箱！") ;
        }
        try {
            QQSMSUtils.testMail(email,emailCode);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("邮箱格式错误！") ;
        }
        redisCache.setCacheObject(email + ":" + emailCode,emailCode , 5, TimeUnit.MINUTES);
        log.info("邮箱验证码为 ->{}",emailCode);
        return AjaxResult.success("验证码发送成功，有效期为5分钟，请前往qq邮箱中获取验证码。") ;
    }
}
